﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]

    

	public class HYPipeConnectBranchPipe : HYExternalCommand
	{
		public override void FilterProcess()
		{
            base.FilterViewType.Add((ViewType)4);
			base.FilterProcess();
		}

		public override Result HYExecute(ref string TranName)
		{
			TranName = "主管连接支管";
			ISelectionFilter selectionFilter = new SprinklersPipeSelectionFilter();
			HYPipeConnect hypipeConnect = new HYPipeConnect();
			for (;;)
			{
				Reference reference = base.Sel.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, selectionFilter, "请选择一根喷淋系统主管道");
				Pipe pipe = base.Doc.GetElementById(reference.ElementId) as Pipe;
				SubTransaction subTransaction = new SubTransaction(base.Doc);
				try
				{
					IList<Element> list = new List<Element>();
					IList<Element> list2 = base.Sel.PickElementsByRectangle(selectionFilter, "请框选需要连接的支管");
					if (list2.Count != 0)
					{
						subTransaction.Start();
						foreach (Element element in list2)
						{
							bool flag = true;
							if (pipe != null && element.Id != pipe.Id)
							{
								foreach (Connector connector in YJKRevitTools.GetPipeConnConnector(element as Pipe))
								{
									Connector connectConnector = YJKRevitTools.GetConnectConnector(connector);
									if (-2008099 == connectConnector.Owner.Category.Id.IntegerValue)
									{
										flag = false;
										break;
									}
								}
								if (flag)
								{
									list.Add(element);
								}
							}
						}
						if (!hypipeConnect.PipeConnBranchPipe(base.Doc, pipe, list))
						{
							YJKMessageBox.Information("连接失败！");
							break;
						}
						subTransaction.Commit();
					}
					continue;
				}
				catch (Autodesk.Revit.Exceptions.OperationCanceledException)
				{
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				catch (Exception ex)
				{
					YJKMessageBox.Error(ex.Message);
					continue;
				}
				finally
				{
					if (subTransaction != null)
					{
						TransactionStatus status = subTransaction.GetStatus();
						if (status == (TransactionStatus)1)
						{
							subTransaction.Commit();
						}
						else if (status == (TransactionStatus)5)
						{
							subTransaction.RollBack();
						}
					}
				}
				break;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
